﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
// 
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
// 
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.Text;
using Aurora.AI.Abstractions.ObjectModels.ResponseModels.VideoResponseModel;
using Aurora.AI.Common.Extensions;
using Aurora.AI.MetaGLM.Models.RequestModels;
using Aurora.AI.MetaGLM.Models.ResponseModels.VideosGenerationModels;

namespace Aurora.AI.MetaGLM.Modules;

public class Videos
{
    private static readonly int API_TOKEN_TTL_SECONDS = 60 * 5;
    private HttpClient HttpClient = new();


    private IEnumerable<string> GenerateBase(VideoRequestBase requestBody, string apiKey)
    {
        var json = AuroraAIJsonSerializer.Serialize(requestBody);
        var data = new StringContent(json, Encoding.UTF8, "application/json");
        var api_key = AuthenticationUtils.GenerateToken(apiKey, API_TOKEN_TTL_SECONDS);

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://open.bigmodel.cn/api/paas/v4/videos/generations"),
            Content = data,
            Headers =
            {
                { "Authorization", api_key }
            },
        };

        var response = HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;
       
        var stream = response.Content.ReadAsStreamAsync().Result;
        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            yield return Encoding.UTF8.GetString(buffer, 0, bytesRead);
        }
    }

    private IEnumerable<string> QueryTaskBase(string taskId, string apiKey)
    {
        var api_key = AuthenticationUtils.GenerateToken(apiKey, API_TOKEN_TTL_SECONDS);

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("https://open.bigmodel.cn/api/paas/v4/async-result/" + taskId),
            Headers =
            {
                { "Authorization", api_key }
            },
        };

        var response = HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;
        var stream1 = response.Content.ReadAsStringAsync().Result;
        var stream = response.Content.ReadAsStreamAsync().Result;
        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            yield return Encoding.UTF8.GetString(buffer, 0, bytesRead);
        }
    }

    /// <summary>
    /// 生成图片-任务
    /// </summary>
    /// <param name="requestBody"></param>
    /// <param name="apiKey"></param>
    /// <returns></returns>
    public VideoResponseBase GenerationTask(VideoRequestBase requestBody, string apiKey)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var str in GenerateBase(requestBody, apiKey))
        {
            sb.Append(str);
        }

        return sb.ToString().FromJson<VideoResponseBase>();
    }


    /// <summary>
    /// 生成图片-查询
    /// </summary>
    /// <param name="taskId"></param>
    /// <param name="apiKey"></param>
    /// <returns></returns>
    public VideoResponseBase GenerationQuery(string taskId, string apiKey)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var str in QueryTaskBase(taskId, apiKey))
        {
            sb.Append(str);
        }

        return sb.ToString().FromJson<VideoResponseBase>();
    }
}